package nconv.convert;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by xiaobyu on 4/26/2016.
 */
public class DocUtils {
    
    public static final String[] SPEC_NAME_ARRAY = new String[] {
            "23002",
            "23107",
            "23203",
            "23401",
            "23402",
            "29212",
            "29213",
            "29214",
            "29215",
            "29217",
            "29219",
            "29229",
            "29329",
            "29335",
            "29154"
    };

    static Pattern tgppFileNamePattern = Pattern.compile("^\\d{5,5}-\\w{3,3}\\.doc$");

    private static Map<String, String> specNameFileMap = null;

    public static void setSpecFileNames(String[] specNames) {
        specNameFileMap = new HashMap<>();
        File inputDir = new File("input");
        assert inputDir.isDirectory();
        File[] files = inputDir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return tgppFileNamePattern.matcher(name).find();
            }
        });

        for (File file : files) {
            String fileName = file.getName();
            String spec = fileName.substring(0, fileName.indexOf('-'));
            if (specNameFileMap.containsKey(spec)) {
                String existing = specNameFileMap.get(spec);
                if (fileName.compareTo(existing) > 0) {
                    specNameFileMap.put(spec, fileName);
                }
            } else {
                specNameFileMap.put(spec, fileName);
            }
        }
    }

    public static String getSpecDocFileName(String spec) {
        if (specNameFileMap == null) {
            setSpecFileNames(SPEC_NAME_ARRAY);
        }
        return specNameFileMap.get(spec);
    }

    public static Map<String, String> getSpecDocFileMap() {
        if (specNameFileMap == null) {
            setSpecFileNames(SPEC_NAME_ARRAY);
        }
        return specNameFileMap;
    }

    public static void main(String[] args) {
        setSpecFileNames(SPEC_NAME_ARRAY);
        for (String spec : SPEC_NAME_ARRAY) {
            if (specNameFileMap.get(spec) == null) {
                System.out.println("Failed to locate a word document for spec: " + spec);
            }
        }
        System.out.println(specNameFileMap);
    }
}
